package com.academic.system.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.academic.system.controller.request.LoginRequest;
import com.academic.system.model.User;
import com.academic.system.repository.UserRepository;
import com.academic.system.security.UserDetailsImpl;
import com.academic.system.service.UserService;

/**
 * 身份验证控制器
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    UserRepository userRepository;
    
    @Autowired
    UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public ResponseEntity<?> authenticateUser(
            @Valid @RequestBody LoginRequest loginRequest,
            HttpServletRequest request,
            HttpServletResponse response) {
        try {
            System.out.println("接收到登录请求 - 用户名: " + loginRequest.getUsername());
            
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));

            SecurityContextHolder.getContext().setAuthentication(authentication);
            
            // 将认证信息保存到session中
            request.getSession().setAttribute(
                HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, 
                SecurityContextHolder.getContext()
            );
            
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            User user = userRepository.findById(userDetails.getId());
            
            // 将用户信息保存到Session中，供个人信息接口使用
            if (user != null) {
                request.getSession().setAttribute("currentUser", user);
                // 更新最后登录时间
                userService.updateLastLoginTime(user.getId());
            }
            
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("id", userDetails.getId());
            responseData.put("username", userDetails.getUsername());
            responseData.put("role", userDetails.getRole());
            if (user != null) {
                responseData.put("realName", user.getRealName());
            }
            
            return ResponseEntity.ok(responseData);
        } catch (Exception e) {
            Map<String, String> errorResponse = new HashMap<>();
            errorResponse.put("message", "用户名或密码错误");
            return ResponseEntity.status(401).body(errorResponse);
        }
    }
    
    /**
     * 获取当前登录用户信息
     */
    @GetMapping("/user")
    public ResponseEntity<?> getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated() || 
                "anonymousUser".equals(authentication.getPrincipal())) {
            return ResponseEntity.status(401).body("User not authenticated");
        }
        
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        User user = userRepository.findById(userDetails.getId());
        
        Map<String, Object> response = new HashMap<>();
        response.put("id", userDetails.getId());
        response.put("username", userDetails.getUsername());
        response.put("role", userDetails.getRole());
        if (user != null) {
            response.put("realName", user.getRealName());
        }
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 用户注销
     */
    @PostMapping("/logout")
    public ResponseEntity<?> logoutUser(HttpServletRequest request) {
        // 清理Spring Security上下文
        SecurityContextHolder.clearContext();
        
        // 清理Session中的用户信息
        request.getSession().removeAttribute("currentUser");
        request.getSession().removeAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY);
        
        // 使Session失效
        request.getSession().invalidate();
        
        Map<String, String> response = new HashMap<>();
        response.put("message", "注销成功");
        return ResponseEntity.ok(response);
    }
} 